using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Authorization;
using Volo.Abp.DependencyInjection;

namespace CKY.AgentPlatform.Authorization
{
    /// <summary>
    /// 权限过滤器
    /// </summary>
    public class PermissionFilter : IAsyncActionFilter, ITransientDependency
    {
        private readonly PermissionCheckerHelper _permissionCheckerHelper;

        public PermissionFilter(PermissionCheckerHelper permissionCheckerHelper)
        {
            _permissionCheckerHelper = permissionCheckerHelper;
        }

        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 获取权限特性
            var permissionAttribute = context.ActionDescriptor.EndpointMetadata
                .OfType<RequirePermissionAttribute>()
                .FirstOrDefault();

            var roleAttribute = context.ActionDescriptor.EndpointMetadata
                .OfType<RequireRoleAttribute>()
                .FirstOrDefault();

            try
            {
                // 检查角色权限
                if (roleAttribute != null)
                {
                    await CheckRolePermissionAsync(roleAttribute);
                }

                // 检查功能权限
                if (permissionAttribute != null)
                {
                    await CheckFunctionPermissionAsync(permissionAttribute);
                }

                await next();
            }
            catch (AbpAuthorizationException ex)
            {
                context.Result = new ObjectResult(new
                {
                    success = false,
                    error = ex.Message,
                    code = 403
                })
                {
                    StatusCode = 403
                };
            }
        }

        /// <summary>
        /// 检查角色权限
        /// </summary>
        private async Task CheckRolePermissionAsync(RequireRoleAttribute roleAttribute)
        {
            if (roleAttribute.Roles.Contains("admin") && !_permissionCheckerHelper.IsAdmin())
            {
                throw new AbpAuthorizationException("需要管理员权限");
            }

            if (roleAttribute.Roles.Contains("system-admin") && !_permissionCheckerHelper.IsSystemAdmin())
            {
                throw new AbpAuthorizationException("需要系统管理员权限");
            }

            // 检查其他角色
            foreach (var role in roleAttribute.Roles)
            {
                if (role != "admin" && role != "system-admin")
                {
                    // 这里可以根据需要扩展角色检查逻辑
                    await Task.CompletedTask;
                }
            }
        }

        /// <summary>
        /// 检查功能权限
        /// </summary>
        private async Task CheckFunctionPermissionAsync(RequirePermissionAttribute permissionAttribute)
        {
            if (permissionAttribute.RequireAll)
            {
                await _permissionCheckerHelper.CheckAllPermissionsAsync(permissionAttribute.Permissions);
            }
            else
            {
                await _permissionCheckerHelper.CheckAnyPermissionAsync(permissionAttribute.Permissions);
            }
        }
    }

    /// <summary>
    /// 验证过滤器
    /// </summary>
    public class ValidationFilter : IAsyncActionFilter, ITransientDependency
    {
        public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            // 检查模型状态
            if (!context.ModelState.IsValid)
            {
                var errors = context.ModelState.Values
                    .SelectMany(v => v.Errors)
                    .Select(e => e.ErrorMessage)
                    .Where(e => !string.IsNullOrEmpty(e))
                    .ToList();

                context.Result = new ObjectResult(new
                {
                    success = false,
                    error = "数据验证失败",
                    details = errors
                })
                {
                    StatusCode = 400
                };
                return;
            }

            // 检查必需参数
            foreach (var parameter in context.ActionDescriptor.Parameters)
            {
                if (parameter.BindingInfo?.BindingSource == BindingSource.Body &&
                    !context.ActionArguments.ContainsKey(parameter.Name))
                {
                    context.Result = new ObjectResult(new
                    {
                        success = false,
                        error = $"缺少必需参数: {parameter.Name}"
                    })
                    {
                        StatusCode = 400
                    };
                    return;
                }
            }

            await next();
        }
    }

    /// <summary>
    /// API特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class ApiVersionAttribute : Attribute
    {
        public string Version { get; }

        public ApiVersionAttribute(string version)
        {
            Version = version;
        }
    }

    /// <summary>
    /// 限流特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class RateLimitAttribute : Attribute
    {
        public int RequestsPerMinute { get; }
        public int RequestsPerHour { get; }

        public RateLimitAttribute(int requestsPerMinute = 60, int requestsPerHour = 3600)
        {
            RequestsPerMinute = requestsPerMinute;
            RequestsPerHour = requestsPerHour;
        }
    }

    /// <summary>
    /// 缓存特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class CacheAttribute : Attribute
    {
        public int DurationSeconds { get; }
        public string Key { get; }

        public CacheAttribute(int durationSeconds = 300, string key = null)
        {
            DurationSeconds = durationSeconds;
            Key = key;
        }
    }

    /// <summary>
    /// 审计日志特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class AuditLogAttribute : Attribute
    {
        public string ActionName { get; }
        public bool LogParameters { get; set; } = true;
        public bool LogResult { get; set; } = false;

        public AuditLogAttribute(string actionName = null)
        {
            ActionName = actionName;
        }
    }

    /// <summary>
    /// 安全特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class SecurityAttribute : Attribute
    {
        public bool RequireHttps { get; set; } = true;
        public bool ValidateAntiForgeryToken { get; set; } = true;
        public bool ValidateCors { get; set; } = true;
    }

    /// <summary>
    /// 数据验证特性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]
    public class ValidateModelAttribute : Attribute
    {
        public bool ValidateAllProperties { get; set; } = true;
        public bool ValidateRequiredFields { get; set; } = true;
        public bool ValidateStringLengths { get; set; } = true;
        public bool ValidateDataTypes { get; set; } = true;
    }
}